import { FileStream } from 'egg';
import { v4 as uuidv4 } from 'uuid';
import * as fs from 'fs';
import * as path from 'path';

class FileUtil {
  static saveImage(stream: FileStream, filename: string) {
    return new Promise((resolve, reject) => {
      const uuid = uuidv4();
      const filenameSplitedArr = filename.split('.');
      const suffix = filenameSplitedArr[filenameSplitedArr.length - 1];
      const curFilename = `${uuid}.${suffix}`;
      const absolutePath = path.resolve(
        __dirname,
        '../public/image',
        curFilename
      );

      const writeStream = fs.createWriteStream(absolutePath);
      stream.pipe(writeStream);
      stream.on('error', reject);
      stream.on('end', () => {
        resolve(curFilename);
      });
    });
  }

  static readImage(filename: string) {
    let stream;

    try {
      const absolutePath = path.resolve(
        __dirname,
        '../public/image',
        filename
      );

      stream = fs.createReadStream(absolutePath);
    } catch (error) {
      console.log(error);
    }

    return stream;
  }

  static deleteImage(filename: string) {
    let result;
    try {
      const absolutePath = path.resolve(
        __dirname,
        '../public/image',
        filename
      );

      result = fs.unlink(absolutePath, function(error) {
        if(error) {
          console.log(error);
          return false;
        }
      });

    } catch (error) {
      console.log(error);
    }

    return result;
  }

}
export default FileUtil;
